package com.examples.springboot.jpa.resources;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import javax.transaction.Transactional;

import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.examples.springboot.jpa.domain.Employee;
import com.examples.springboot.jpa.exception.ResourceNotFoundException;
import com.examples.springboot.jpa.pojos.DepartmentDto;
import com.examples.springboot.jpa.pojos.EmployeeDto;
import com.examples.springboot.jpa.repository.DepartmentRepository;
import com.examples.springboot.jpa.repository.EmployeeRepository;

@Controller
public class EmployeeResource {
  @Autowired
  private EmployeeRepository employeetRepository;
  @Autowired
  private DepartmentRepository departmentRepository;
  @Autowired
  private ModelMapper modelMapper;

  @Transactional
  public List<EmployeeDto> getAll() {
    return StreamSupport.stream(employeetRepository.findAll().spliterator(), false)
        .map((e) -> {
          EmployeeDto dto = modelMapper.map(e, EmployeeDto.class);
          dto.setDepartment(new DepartmentDto(e.getDepartment()));
          return dto;
        }).collect(Collectors.toList());
  }

  public Employee updateEmployee(long employeeId, DepartmentDto dto) {
    return departmentRepository.findById(dto.getId()).map(department -> {
      return employeetRepository.findById(employeeId).map((employee) -> {
        employee.setDepartment(department);
        return employeetRepository.save(employee);
      }).orElseThrow(() -> new ResourceNotFoundException("EmployeeId " + employeeId + " not found"));
    }).orElseThrow(() -> new ResourceNotFoundException("Department " + dto.getId() + " not found"));
  }

  public boolean deleteEmployee(long employeeId) {
   return employeetRepository.findById(employeeId).map((employee) -> {
      employeetRepository.delete(employee);
      return true;
    }).orElseThrow(() -> new ResourceNotFoundException("EmployeeId " + employeeId + " not found"));
  }
}
